#include "AccountHandler.h"
#include "Game.h"
#include "public_define.h"


void CAccountHandler::Init()
{
    CheckUidSet();
}

void CAccountHandler::CheckUidSet()
{
    // int step = (MAX_ACCOUNT - MIN_ACCOUNT)/UID_BUCKET_COUNT;
    for (uint32 i=0; i< UID_BUCKET_COUNT; i++)
    {
        std::string key = S_ALLOCATED_UID_INDEX + std::to_string(i);
        int64_t val = 0;
        m_userinfoRedis->Exists(key, &val);
        if (val == 0)
        {
            m_userinfoRedis->Set(key, std::to_string(UID_BUCKET[i]));
        }
    }
    return;
}

uint32 CAccountHandler::GetNewUidFromRedis()
{
    uint32 uid = 0;
    int index = rand() % UID_BUCKET_COUNT;
    for (uint32 i = 0; i < UID_BUCKET_COUNT; ++i)  //最大尝试次数
    {
        if (m_useout_buckets[index])  // 如果已经耗尽 就直接判断下一个
        {
            index = (index+1)%UID_BUCKET_COUNT;
            continue;
        }

        std::string key = S_ALLOCATED_UID_INDEX + std::to_string(index);
        int64_t val = 0;
        m_userinfoRedis->Incr(key, &val);
        if (val < UID_BUCKET[index+1])
        {
            uid = val;
            break;
        }
        m_useout_buckets[index]=1;  // 标记当前段已经耗尽
        index = (index+1)%UID_BUCKET_COUNT;
        log_error("uid alloc failed, i:%d, index:%d, val:%ld", i, index, val);
    }
    return uid;
}

